// pages/login/index.js
const app = getApp();
var topOpacity = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "登录注册", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent',
      goUrl: ''
    },
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,

    openid: '',
    shareTitle: '',
    shareImg: '',
    is_register: 0,
    showStatement: false, //是否弹出协议框
    showAgreement: false, //单个隐私协议内容
    choose1: false,
    choose2: false,
    choose3: false,
    agreement_title: "用户协议",
    html: '',
    flag: 0,
    rebindToken: '', //换绑凭证
    sessionCode: '',
    isSq: 0
  },
  onPageScroll(t) {
    if (t.scrollTop < 40) {
      topOpacity = 0
      if (this.data.topOpacity != 0) {
        this.setData({
          topOpacity: 0
        })
      }
    } else if (t.scrollTop >= 40) {
      if (topOpacity <= 1) {
        topOpacity = t.scrollTop / 100 - .4
      } else {
        topOpacity = 1
      }
      if (topOpacity <= 1) {
        this.setData({
          topOpacity: topOpacity
        })
      }
    }
  },
  //获取sessionCode
  getSessionCode() {
    var that = this;
    wx.login({
      success: function (res) {
        that.setData({
          sessionCode: res.code
        });
      }
    });
  },
  //获取sessionCode
  getSessionCode() {
    var that = this;
    wx.login({
      success: function (res) {
        that.setData({
          sessionCode: res.code
        });
      }
    });
  },
  //点击本机验证
  getPhoneNumber(e) {
    var that = this;

    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      wx.request({
        url: that.data.baseUrl + 'getPhoneNumber/getPhoneNumber.php', //仅为示例，并非真实的接口地址
        method: 'POST',
        data: {
          'sessionKeyCode': that.data.sessionCode,
          'encryptedData': e.detail.encryptedData,
          'iv': e.detail.iv,
          'openid': that.data.openid
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          if (res.data.status == 1) {
            //获取电话号码成功
            wx.navigateTo({
              url: '/pages/login/index?isBj=1&tel=' + res.data.tel
            });
          } else {
            //获取电话号码失败
            //重新获取sessionCode用于电话号码获取的解密验证
            app.showTip(res.data.msg);
            that.getSessionCode();
            return;
          }
        },
        fail: function () {
          app.showTip('网络错误,获取电话号码失败,请检查您的网络');
          return;
        }
      });
    } else {
      //重新换取解密code
      that.getSessionCode();
    }
  },
  //提示勾选协议
  tipsXy() {
    this.setData({
      showStatement: true
    });
  },

  //点击手机短信码验证
  verificationLogin() {
    var that = this;

    //判断是否同意了隐私协议
    if (wx.getStorageSync('firstXy') == undefined || wx.getStorageSync('firstXy') == '') {
      if (that.data.choose1 == false || that.data.choose2 == false || that.data.choose3 == false) {
        that.setData({
          showStatement: true
        });
        return;
      }
    }
    wx.navigateTo({
      url: '/pages/login/index',
    })
  },
  //14岁协议
  choose1() {
    this.setData({
      // 点击之后进行取反
      choose1: !this.data.choose1
    })
  },
  //用户协议
  choose2() {
    this.setData({
      // 点击之后进行取反
      choose2: !this.data.choose2
    })
  },
  //隐私协议
  choose3() {
    this.setData({
      // 点击之后进行取反
      choose3: !this.data.choose3
    })
  },

  //不同意协议
  disagree() {
    this.setData({
      showStatement: false
    })
  },

  //同意协议
  agree() {
    var choose1 = this.data.choose1;
    var choose2 = this.data.choose2;
    var choose3 = this.data.choose3;

    if (!choose1) {
      app.showTip("请确认年龄信息与实际年龄相符");
      return;
    }
    if (!choose2) {
      app.showTip("请勾选并同意《麓悦江城线上中心小程序用户服务协议》");
      return;
    }
    if (!choose3) {
      app.showTip("请勾选并同意《麓悦江城线上中心小程序隐私权政策》");
      return;
    }

    this.setData({
      showStatement: false,
      isSq: 1
    });
    wx.setStorageSync('firstXy', 1);
  },

  //关闭隐私详情
  closeAgreement() {
    this.setData({
      showAgreement: false,
      html: '',
      agreement_title: ''
    })
  },

  //查询协议内容
  getXyContent(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    wx.showLoading({
      title: '数据加载中...'
    });
    wx.request({
      url: that.data.baseUrl + 'getXyContent.php',
      method: 'POST',
      data: {
        'id': id
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //后台请求成功
          that.setData({
            html: that.formatRichText(res.data.info['content']),
            agreement_title: res.data.info.title,
            showAgreement: true,
          })
        } else {
          //后台请求失败
          app.showTip(res.data.msg);

        }
      },
      fail: function (res) {
        wx.hideLoading();
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;

    //判断是否同意过协议
    if (wx.getStorageSync('firstXy') == '' || wx.getStorageSync('firstXy') == undefined) {
      that.setData({
        showStatement: true
      });
    } else {
      that.setData({
        isSq: 1
      });
    }

    //生成电话号码解密的code
    that.getSessionCode();

    //获取缓存中的openid
    var openid = wx.getStorageSync('ly24_openid');

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });
              },
              fail: function (res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });
    }

    //调用分享
    that.getShareInfo();
  },

  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo.php',
      method: 'POST',
      data: {

      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function (res) {}
    });
  },


  /**
   * 处理富文本里的图片宽度自适应
   * 1.去掉img标签里的style、width、height属性
   * 2.img标签添加style属性：max-width:100%;height:auto
   * 3.修改所有style里的width属性为max-width:100%
   * 4.去掉<br/>标签
   * @param html
   * @returns {void|string|*}
   */
  formatRichText(html) {
    let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
      match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
      match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
      match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
      return match;
    });
    newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
      match = match.replace(/width:[^;]+;/gi, 'width:100%;').replace(/width:[^;]+;/gi, 'width:100%;');
      return match;
    });
    newContent = newContent.replace(/<br[^>]*\/>/gi, '');
    newContent = newContent.replace(/\<img/gi, '<img style="width:100%;height:auto;display:block;margin:10px 0;"');
    return newContent;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    return {
      title: that.data.shareTitle,
      path: '/pages/index/index',
      imageUrl: that.data.shareImg,
      success: function (res) {

      },
      fail: function (res) {

      }
    }
  }
})